use std::collections::HashMap;
use std::process::{Command, Stdio};
use log::{info, warn, error};

// Shell服务
pub struct ShellService {
    pub running: bool,
    pub current_directory: String,
    pub environment_variables: HashMap<String, String>,
    pub command_history: Vec<String>,
    pub max_history_size: usize,
}

impl Default for ShellService {
    fn default() -> Self {
        let mut env_vars = HashMap::new();
        env_vars.insert("PATH".to_string(), "/usr/bin:/bin:/usr/local/bin".to_string());
        env_vars.insert("HOME".to_string(), "/home/user".to_string());
        env_vars.insert("USER".to_string(), "user".to_string());
        
        Self {
            running: false,
            current_directory: "/home/user".to_string(),
            environment_variables: env_vars,
            command_history: Vec::new(),
            max_history_size: 1000,
        }
    }
}

impl ShellService {
    pub fn new() -> Self {
        println!("初始化Shell服务");
        Self::default()
    }
    
    pub fn start(&mut self) -> Result<(), String> {
        if self.running {
            return Err("Shell服务已经运行".to_string());
        }
        
        self.running = true;
        info!("Shell服务已启动");
        Ok(())
    }
    
    pub fn stop(&mut self) -> Result<(), String> {
        if !self.running {
            return Err("Shell服务未运行".to_string());
        }
        
        self.running = false;
        info!("Shell服务已停止");
        Ok(())
    }
    
    /// 执行Shell命令
    pub fn execute_command(&mut self, command: &str, args: &[&str]) -> Result<(String, i32), String> {
        if !self.running {
            return Err("Shell服务未运行".to_string());
        }
        
        let full_command = format!("{} {}", command, args.join(" "));
        self.add_to_history(&full_command);
        
        info!("执行命令: {}", full_command);
        
        // 模拟命令执行
        match command {
            "ls" => self.execute_ls(args),
            "cd" => self.execute_cd(args),
            "pwd" => self.execute_pwd(),
            "echo" => self.execute_echo(args),
            "cat" => self.execute_cat(args),
            "mkdir" => self.execute_mkdir(args),
            "rm" => self.execute_rm(args),
            "cp" => self.execute_cp(args),
            "mv" => self.execute_mv(args),
            _ => self.execute_external_command(command, args),
        }
    }
    
    /// 添加命令到历史记录
    pub fn add_to_history(&mut self, command: &str) {
        if self.command_history.len() >= self.max_history_size {
            self.command_history.remove(0);
        }
        self.command_history.push(command.to_string());
    }
    
    /// 获取命令历史
    pub fn get_command_history(&self) -> &[String] {
        &self.command_history
    }
    
    /// 设置环境变量
    pub fn set_environment_variable(&mut self, key: &str, value: &str) -> Result<(), String> {
        if !self.running {
            return Err("Shell服务未运行".to_string());
        }
        
        self.environment_variables.insert(key.to_string(), value.to_string());
        info!("设置环境变量: {}={}", key, value);
        Ok(())
    }
    
    /// 获取环境变量
    pub fn get_environment_variable(&self, key: &str) -> Option<&str> {
        self.environment_variables.get(key).map(|s| s.as_str())
    }
    
    /// 改变当前目录
    pub fn change_directory(&mut self, path: &str) -> Result<(), String> {
        if !self.running {
            return Err("Shell服务未运行".to_string());
        }
        
        // 简化路径处理
        let new_path = if path.starts_with('/') {
            path.to_string()
        } else if path == ".." {
            // 处理上级目录
            if let Some(pos) = self.current_directory.rfind('/') {
                if pos > 0 {
                    self.current_directory[..pos].to_string()
                } else {
                    "/".to_string()
                }
            } else {
                "/".to_string()
            }
        } else if path == "." {
            self.current_directory.clone()
        } else {
            format!("{}/{}", self.current_directory, path)
        };
        
        self.current_directory = new_path;
        info!("改变目录到: {}", self.current_directory);
        Ok(())
    }
    
    /// 获取当前目录
    pub fn get_current_directory(&self) -> &str {
        &self.current_directory
    }
    
    // 内置命令实现
    fn execute_ls(&self, args: &[&str]) -> Result<(String, i32), String> {
        let path = if args.is_empty() {
            &self.current_directory
        } else {
            args[0]
        };
        
        let output = format!("drwxr-xr-x 2 user user 4096 Jan 1 00:00 .\n\
                            drwxr-xr-x 3 user user 4096 Jan 1 00:00 ..\n\
                            -rw-r--r-- 1 user user 1024 Jan 1 00:00 file1.txt\n\
                            -rw-r--r-- 1 user user 2048 Jan 1 00:00 file2.txt\n\
                            drwxr-xr-x 2 user user 4096 Jan 1 00:00 documents");
        
        Ok((output, 0))
    }
    
    fn execute_cd(&mut self, args: &[&str]) -> Result<(String, i32), String> {
        if args.is_empty() {
            self.change_directory("/home/user")?;
        } else {
            self.change_directory(args[0])?;
        }
        Ok(("".to_string(), 0))
    }
    
    fn execute_pwd(&self) -> Result<(String, i32), String> {
        Ok((self.current_directory.clone(), 0))
    }
    
    fn execute_echo(&self, args: &[&str]) -> Result<(String, i32), String> {
        let output = args.join(" ");
        Ok((output, 0))
    }
    
    fn execute_cat(&self, args: &[&str]) -> Result<(String, i32), String> {
        if args.is_empty() {
            return Ok(("用法: cat <文件名>".to_string(), 1));
        }
        
        let filename = args[0];
        let content = format!("这是文件 {} 的内容\n行1\n行2\n行3", filename);
        Ok((content, 0))
    }
    
    fn execute_mkdir(&self, args: &[&str]) -> Result<(String, i32), String> {
        if args.is_empty() {
            return Ok(("用法: mkdir <目录名>".to_string(), 1));
        }
        
        let dirname = args[0];
        Ok((format!("创建目录: {}", dirname), 0))
    }
    
    fn execute_rm(&self, args: &[&str]) -> Result<(String, i32), String> {
        if args.is_empty() {
            return Ok(("用法: rm <文件名>".to_string(), 1));
        }
        
        let filename = args[0];
        Ok((format!("删除文件: {}", filename), 0))
    }
    
    fn execute_cp(&self, args: &[&str]) -> Result<(String, i32), String> {
        if args.len() < 2 {
            return Ok(("用法: cp <源文件> <目标文件>".to_string(), 1));
        }
        
        let source = args[0];
        let target = args[1];
        Ok((format!("复制文件: {} -> {}", source, target), 0))
    }
    
    fn execute_mv(&self, args: &[&str]) -> Result<(String, i32), String> {
        if args.len() < 2 {
            return Ok(("用法: mv <源文件> <目标文件>".to_string(), 1));
        }
        
        let source = args[0];
        let target = args[1];
        Ok((format!("移动文件: {} -> {}", source, target), 0))
    }
    
    fn execute_external_command(&self, command: &str, args: &[&str]) -> Result<(String, i32), String> {
        // 模拟外部命令执行
        let output = format!("执行外部命令: {} {}", command, args.join(" "));
        Ok((output, 0))
    }
}